<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'mold:keep:asdMoldKeep:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <template #footer>
      <div class="flex justify-end items-center">
        <Button @click="handleHistory" class="flex"> 查看历史 </Button>
        <BpmButton
          v-model:bpmEntity="record"
          bpmEntityKey="id"
          formKey="ASD_MOLD_KEEP"
          completeText="提交"
          :loading="loadingRef"
          :auth="'mold:keep:asdMoldKeep:edit'"
          @complete="handleSubmit"
          @success="handleSuccess"
          @close="closeDrawer"
        />
      </div>
      <HistoryList ref="historyListRef" />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMoldKeepAsdMoldKeepForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { AsdMoldKeep, asdMoldKeepSave, asdMoldKeepForm } from '/@/api/mold/keep/asdMoldKeep';
  import { BpmButton } from '/@/components/Bpm';
  import { empUserTreeData } from '/@/api/sys/empUser';
  import { officeTreeData } from '/@/api/sys/office';
  import { Button } from 'ant-design-vue';
  import HistoryList from './historyList.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('mold.keep.asdMoldKeep');
  const { showMessage } = useMessage();
  const record = ref<AsdMoldKeep>({} as AsdMoldKeep);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增保养记录') : t('编辑保养记录'),
  }));

  const loadingRef = ref(false);
  const historyListRef = ref();
  const step = ref<string>('');

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工装名称'),
      field: 'moldCode',
      fieldLabel: 'basMold.name',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        return {
          selectType: 'moldSelect',
          onSelect: async (values) => {
            console.log(values);
            formModel['moldCode'] = values[0].code;
            formModel['lastNum'] = values[0].lastNum;
            formModel['basMold.caddcode'] = values[0].caddcode;
            formModel['basMold.clsCode'] = values[0].clsCode;

            formModel['useByIqty'] = values[0].useBlQty;
            formModel['byIqty'] = values[0].byQty || 0;
            formModel['bySyIqty'] = values[0].byQty - values[0].useBlQty;
            formModel['useIqty'] = values[0].useQty || 0;

            // if(values[0].useQty && values[0].byQty && values[0].useQty > values[0].byQty){
            //   formModel['useQty'] = values[0].useQty - values[0].byQty;
            //   formModel['iqty'] = values[0].byQty - formModel['useQty'];
            // }else if(values[0].useQty && values[0].byQty && values[0].useQty < values[0].byQty){
            //   formModel['iqty'] = values[0].byQty - values[0].useQty;
            // }
          },
        };
      },
      required: true,
    },
    {
      label: t('工装代码'),
      field: 'basMold.caddcode',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('工装类型'),
      field: 'basMold.clsCode',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('工装尾号'),
      field: 'lastNum',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      // required: true,
    },
    {
      label: t('累计加工数'),
      field: 'useIqty',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
      },
      // ifShow: false,
    },
    {
      label: t('加工次数'),
      field: 'useByIqty',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('保养周期'),
      field: 'byIqty',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('保养剩余次数'),
      field: 'bySyIqty',
      component: 'InputNumber',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('保养时长'),
      field: 'keepTime',
      component: 'InputNumber',
      componentProps: {
        placeholder: t('单位：小时'),
        addonAfter: '小时',
      },
    },
    {
      label: t('保养内容'),
      field: 'keepDesc',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
    },
    {
      label: t('送保人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      show: false,
    },
    {
      label: t('模具保养人'),
      field: 'repairName',
      fieldLabel: 'empUser.userName',
      component: 'TreeSelect',
      componentProps: {
        // api: empUserTreeData,
        api: officeTreeData,
        allowClear: true,
        params: { isLoadUser: true, userIdPrefix: '' },
        canSelectParent: false,
        treeCheckable: false,
      },
    },
    {
      label: t('工装变更'),
      field: 'moldType',
      component: 'Select',
      componentProps: {
        dictType: 'moldType',
        maxlength: 64,
      },
      required: true,
      // step 等于 step2 时，显示
      ifShow: () => {
        return step.value == 'step2';
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    step.value = data['bpm.activityId'];
    const res = await asdMoldKeepForm(data);
    record.value = (res.asdMoldKeep || {}) as AsdMoldKeep;
    record.value.__t = new Date().getTime();
    record.value.moldCode ? '' : (record.value.moldCode = data['basMold.caddcode']);
    record.value.basMold?.name ?? (record.value.basMold = { name: data.name });
    console.log(data);
    record.value.basMold.caddcode ? '' : (record.value.basMold.caddcode = data['moldCode']);
    record.value.basMold.clsCode ? '' : (record.value.basMold.clsCode = data['basMold.clsCode']);

    // if(data.useQty && data.byQty && data.useQty > data.byQty){
    //   record.value.useQty = data.useQty - data.byQty;
    //   record.value.iqty = data.byQty - record.value.useQty;
    // }else if(data.useQty && data.byQty && data.useQty < data.byQty){
    //   record.value.iqty = data.byQty - data.useQty;
    // }
    record.value.useByIqty ? '' : (record.value.useByIqty = data.useBlQty);
    if (data.byIqty) {
      record.value.byIqty ? '' : (record.value.byIqty = data.byQty);
    } else {
      record.value.byIqty ? '' : (record.value.byIqty = 0);
    }
    // record.value.byQty ? '' : record.value.byQty = data.byQty;
    record.value.bySyIqty ? '' : (record.value.bySyIqty = data.byQty - data.useBlQty);

    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      console.log('submit', params, data, record);
      const res = await asdMoldKeepSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }

  function handleHistory() {
    console.log(record.value);
    historyListRef.value?.open({
      moldCode: record.value.moldCode,
      lastNum: record.value.lastNum,
    });
  }
</script>
